from asgiref.sync import sync_to_async
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.views import View
from django.db.models import Sum, Prefetch
from django.utils import timezone

from core.schemas import RestaurantSchema, RestaurantSimpleSchema
from .models import Restaurant, Rating, Sale, StaffRestaurant, Staff


class Index(View):

    def get(self, request, *args, **kwargs):
        restaurant_prefetch = Prefetch(
            'restaurant',
            queryset=Restaurant.objects.all(),
        )
        staff_prefetch = Prefetch(
            'staff',
            queryset=Staff.objects.all(),
        )
        # jobs = StaffRestaurant.objects.prefetch_related(restaurant_prefetch, staff_prefetch).all()
        data = []
        # for job in jobs:
        #     print(job.staff.name)
        #     print(job.restaurant.name)
        staff_restaurant_prefetch = Prefetch(
            'staff_restaurants',
            queryset=StaffRestaurant.objects.prefetch_related(
                staff_prefetch).all()
        )
        staffs_prefetch = Prefetch(
            'staffs',
            queryset=Staff.objects.all(),
        )
        restaurants = Restaurant.objects.prefetch_related(
            staff_restaurant_prefetch)
        for restaurant in restaurants:
            d = {
                'name': restaurant.name,
                'staffs': []
            }
            for s in restaurant.staff_restaurants.all():
                d['staffs'].append({
                    'salary': s.salary,
                    'name': s.staff.name,
                })
            data.append(d)

        return JsonResponse(data=data, safe=False)


async def restaurant_detail(request, pk: int):
    restaurant = await sync_to_async(get_object_or_404)(Restaurant, pk=pk)
    print(restaurant.get_absolute_url())
    restaurant = await sync_to_async(RestaurantSimpleSchema.from_orm)(restaurant)
    return JsonResponse(data=restaurant.model_dump(), safe=False)
